/**
 * 
 */
package com.zito.manager;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.downlove.common.RequestContext;
import com.downlove.common.Storage.FileInfo;
import com.downlove.common.StorageService;
import com.downlove.database.POJO;
import com.zito.ErrMsgException;
import com.zito.bean.Electronicfiles;

/**
 * @author YunHai.Jiang
 * 
 */
public class ElectronicfilesManager {

	// 限定文件大小
	int fileSize = 10240 * 1024;

	/**
	 * 附件上传
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public Map<String, Object> uploadFiles() throws ErrMsgException,
			IOException {
		RequestContext rc = RequestContext.get();
		Electronicfiles obj = new Electronicfiles();
		Enumeration<String> files = rc.getFileNames();
		FileInfo info = null;
		long tmpFileid = -1L;
		while (files.hasMoreElements()) {
			String filename = files.nextElement();
			File attFile = rc.file(filename);
			if (attFile.length() > fileSize) {
				throw new ErrMsgException("您上传的- " + attFile.getName()
						+ " -文件过大，系统仅允许上传：" + fileSize / 1024 + "K 大小的文件");
			}
			info = StorageService.FILES.save(attFile).getFileInfo();
			tmpFileid = obj.fromFileinfo(info, rc.param("identifies"));
		}
		Map<String, Object> tmpMap = new HashMap<String, Object>();
		tmpMap.put("info", info);
		tmpMap.put("tmpFileid", tmpFileid);
		return tmpMap;
	}

	/**
	 * 删除文章中指定的一个附件
	 * 
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean deleteOneArticleFile() throws ErrMsgException,
			IOException {
		RequestContext rc = RequestContext.get();
		Electronicfiles obj = new Electronicfiles();
		obj = new Electronicfiles();
		obj.setId(rc.param("id", -1L));
		if (obj.getId() == -1L)
			return false;
		Electronicfiles temp = obj.Get(obj.getId());
		boolean flag = obj.Delete();
		if (flag) {
			StorageService.EMPTY.delete(temp.getFileserverpath());
		}
		return flag;
	}
	
	public List<? extends POJO> list(Long electronicid) {
		Electronicfiles obj = new Electronicfiles();
		return obj.forElectronicList(electronicid);
	}
}
